<?php
// +---------------------------------------------------------------------------------
// | Url参数为restful风格，访问示例（xxxx为游戏名字，如立方酷跑，为cuberace）:
// |
// | https://gamedev.elloworld.cn/xxxx/index/doRegByCode/wxapp_code/xdsdsdsa/
// | 说明：上面地址只有一个参数wxapp_code，值为xdsdsdsa
// +---------------------------------------------------------------------------------
namespace app\controller;


use app\BaseController;
use think\facade\Request;
use tool\OutPut;
use tool\Utils;
use tool\WxSDK;


class Index extends BaseController
{
    protected $middleware = [
        \app\middleware\Auth::class => ['only' => ['getSignPackage']],
    ];

    /**
     * 第三方提供的授权获取信息接口
     */
    public function auth()
    {
        $url = $_REQUEST['url'] ?? 'https://idea.elloworld.cn/sanyuan/index.html';

        $appId     = config('third.wx_app_id');
        $appSecret = config('third.wx_app_secret');

        $third_code = Utils::str_to_ascii($url);
        $redirectUri = urlencode(url('oauth2Callback')->https()->domain(true)->suffix('')->build());
        $redirectUri = str_replace('public%2F', '', $redirectUri);
        $wxsdk = new WxSDK($appId, $appSecret);
        $wxsdk->getAuthUrl($redirectUri, 'snsapi_userinfo',  $third_code);
    }

    /**
     * 授权回调函数
     */
    public function oauth2Callback()
    {
        $appId     = config('third.wx_app_id');
        $appSecret = config('third.wx_app_secret');

        $code = Request::param('code');
        $wxsdk = new WxSDK($appId, $appSecret);
        $userInfo = $wxsdk->oauth2Callback($code);
        $openid = $userInfo['openid'];
        $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
        $headimgurl = isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '';

        $state = Request::param('state');;
        $url = Utils::ascii_to_str($state);
        $url = strpos($url, '?') ? $url . '&'  : $url . '?';
        $url .= 'openid=' . urlencode($openid) . '&nickname=' . urlencode($nickname) . '&headimgurl=' . urlencode($headimgurl);
        header('location: ' . $url);
        exit(0);
    }

    /**
     * 用户微信分享接口
     */
    public function getSignPackage()
    {
        $preUrl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $url    = isset($_REQUEST['url']) ? $_REQUEST['url'] : $preUrl;
        $appId     = config('extra.wx_app_id');
        $appSecret = config('extra.wx_app_secret');

        $sdk = new WxSDK($appId, $appSecret);
        $signPackage = $sdk->getSignPackage($url);

        return OutPut::success($signPackage);
    }
}
